//
//  OnExten.m
//  Jyxt
//
//  Created by 刘日 on 17/5/18.
//  Copyright © 2017年 DaLian Rental Housing Management. All rights reserved.
//

#import "OnExten.h"

@implementation OnExten

- (instancetype)initWithMixView:(LemonMixView *)mixView webView:(WKWebView *)webView{
    if (self = [super initWithMixView:mixView webView:webView]) {
        [webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    }
    return self;
}

- (NSMutableArray<LM_MIX_ON_LOAD_COMPLETE> *)onLoadCompleteArr{
    if (!_onLoadCompleteArr) {
        _onLoadCompleteArr = [NSMutableArray array];
    }
    return _onLoadCompleteArr;
}

- (NSMutableArray<LM_MIX_ON_LOAD_PROGRESS_CHANGE> *)onProgressChangeArr{
    if (!_onProgressChangeArr) {
        _onProgressChangeArr = [NSMutableArray array];
    }
    return _onProgressChangeArr;
}

- (NSMutableArray<LM_MIX_ON_RECEIVE_JS_MSG> *)onReceiveJSMsgArr{
    if (!_onReceiveJSMsgArr){
        _onReceiveJSMsgArr = [NSMutableArray array];
    }
    return _onReceiveJSMsgArr;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        NSLog(@"加载进度：%f" , self.webView.estimatedProgress);
        if (self.webView.estimatedProgress >= 1){// 加载完成
            for (LM_MIX_ON_LOAD_COMPLETE callback in self.onLoadCompleteArr) {
                callback(self.mixView);
            }
        }
        for (LM_MIX_ON_LOAD_PROGRESS_CHANGE callback in self.onProgressChangeArr) {
            callback(self.mixView , self.webView.estimatedProgress);
        }
    }else{
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

- (void)addOnLoadCompleteCallback: (LM_MIX_ON_LOAD_COMPLETE)loadComplete{
    [self.onLoadCompleteArr addObject: loadComplete];
}

- (void)removeOnLoadCompleteCallback: (LM_MIX_ON_LOAD_COMPLETE)loadComplete{
    [self.onLoadCompleteArr removeObject: loadComplete];
}

- (void)addOnLoadProgressChangeCallback: (LM_MIX_ON_LOAD_PROGRESS_CHANGE)progressChange{
    [self.onProgressChangeArr addObject: progressChange];
}

- (void)removeOnLoadProgressChangeCallback: (LM_MIX_ON_LOAD_PROGRESS_CHANGE)progressChange{
    [self.onProgressChangeArr removeObject: progressChange];
}

- (void)addOnReceiveJSMsgCallback: (LM_MIX_ON_RECEIVE_JS_MSG)jsMsg{
    [self.onReceiveJSMsgArr addObject: jsMsg];
}

- (void)removeOnReceiveJSMsgCallback: (LM_MIX_ON_RECEIVE_JS_MSG)jsMsg{
    [self.onReceiveJSMsgArr removeObject: jsMsg];
}

@end
